package org.znxs.znxsframe.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自定义线程池配置
 */
@Configuration
public class ThreadPoolExecutorConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        /**
         * 线程工厂，用来生成线程
         */
        ThreadFactory threadFactory = new ThreadFactory() {
            private int count = 1;

            @Override
            public Thread newThread(@NotNull Runnable r) {
                // 新建线程
                Thread thread = new Thread(r);
                thread.setName("线程" + count++);
                return thread;
            }
        };


        /**
         * corePoolSize 核心线程数，默认工作线程数
         * maximumPoolSize 线程池大小 最大可以工作线程数
         * keepAliveTime  空闲临时线程存活时间  临时生成的线程存活时间
         * TimeUnit unit  空闲临时线程存活时间 的 时间单位
         * workQueen  工作队列
         * threadFactory  线程工厂  控制每个线程的生成、线程的属性
         * RejectedExecutionHandler  拒绝策略  这个一般都是抛异常 【不用设置】
         */
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2), threadFactory);
        return threadPoolExecutor;

    }
}
